from exts import db
from datetime import datetime
from werkzeug.security import generate_password_hash,check_password_hash


class cmsPermission:
    #全部的权限
    all=0b11111111
    #访问权限
    read=0b00000001
    #管理评论
    talk=0b00000010
    #管理帖子
    ariticle=0b00000100
    #管理板块
    boader=0b00001000
    #管理前台
    m_front=0b00010000
    #管理后台
    m_behind=0b00100000



cms_role_admin=db.Table(
    "cms_role_admin",
    db.Column("role_id",db.Integer,db.ForeignKey("role.id")),
    db.Column("admin_id",db.Integer,db.ForeignKey("admin.id"))
)

class Role(db.Model):
    id=db.Column(db.Integer,primary_key=True,autoincrement=True)
    name=db.Column(db.String(20),nullable=False)
    desc=db.Column(db.String(50))
    creat_time=db.Column(db.DateTime,default=datetime.now)
    permission=db.Column(db.Integer,nullable=False)
    admins=db.relationship("admin",secondary=cms_role_admin,backref="roles")



class admin(db.Model):
    id=db.Column(db.Integer,primary_key=True,autoincrement=True)
    _password=db.Column(db.String(256),nullable=True)
    email=db.Column(db.String(50))
    username=db.Column(db.String(30))
    join_time=db.Column(db.DateTime,default=datetime.now)

    #为了在初始化test类的时候出现了password=password的尴尬场景，写了__init__方法
    def __init__(self,password,username,email):
        self.password=password
        self.username=username
        self.email=email

    @property
    def password(self):
        return self._password

    @password.setter
    def password(self,raw_password):
        self._password=generate_password_hash(raw_password)
        # print(self._password)

    def check_password(self,raw_password):
        if check_password_hash(self.password,raw_password):
            return True
        else:
            return False

    @property
    def get_roles(self):
        if not self.roles:
            return 0
        all_permission=0
        for role in self.roles:
            permiss=role.permission
            all_permission|=permiss
        return all_permission

    def has_permission(self,permission):
        all_permission=self.get_roles
        result=all_permission&permission==permission
        return result

    @property
    def is_develop(self):
        return self.has_permission(cmsPermission.all)
